package cn.innosmart.aq.view.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;

import org.json.JSONException;
import org.json.JSONObject;

import cn.innosmart.aq.R;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;

/**
 * Created by David on 2015/7/15.
 */
public class CountLoginFragment extends BaseFragment implements INetworkInteractUtil {
    private final int CANCEL = -1;
    private ImageView ivBanner;
    private EditText etUsername;
    private EditText etPassword;
    private Button btLogin;
    private TextView tvFindpassword;
    private TextView tvRegister;
    private NetworkInteractUtil interactUtil;
    private View view;
    /**
     * 设置Toolbar
     */
    private Toolbar toolbar;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().setResult(CANCEL);
            getActivity().finish();
            getActivity().overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
        }
    };
    private String Tag = "CountLoginFragment";
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_login:
                    login();
                    break;
                case R.id.tv_findpassword:
//                    switchToFindPasswordFragment();
                    switchToVerifyFragment(2);
                    break;
                case R.id.tv_register:
                    switchToVerifyFragment(1);
                    break;
            }
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    hideLoadingDialog();
                    YoYo.with(Techniques.Shake).playOn(view.findViewById(R.id.et_username));
                    YoYo.with(Techniques.Shake).playOn(view.findViewById(R.id.et_password));
                    if(msg.obj!=null){
                        String message= (String) msg.obj;
                        showToast(message);
                    }else{
                        showToast(getActivity().getString(R.string.login_error_misuser_mispwd));
                    }
                    break;
                case 1:
                    hideLoadingDialog();
                    getActivity().finish();
                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
            }
        }
    };

    private void assignViews(View view) {
        ivBanner = (ImageView) view.findViewById(R.id.iv_banner);
        etUsername = (EditText) view.findViewById(R.id.et_username);
        etPassword = (EditText) view.findViewById(R.id.et_password);
        btLogin = (Button) view.findViewById(R.id.bt_login);
        tvFindpassword = (TextView) view.findViewById(R.id.tv_findpassword);
        tvRegister = (TextView) view.findViewById(R.id.tv_register);
    }

    private void setListener() {
        btLogin.setOnClickListener(mOnClickListener);
        tvFindpassword.setOnClickListener(mOnClickListener);
        tvRegister.setOnClickListener(mOnClickListener);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_countlogin, container, false);
        assignViews(view);
        setListener();
        setBar();
        interactUtil = new NetworkInteractUtil(this);
        return view;
    }

    private void assignData() {
        JSONObject loginJson = SharedUtil.getInstance().readLoginInfo();
        try {
            String username = loginJson.getString("username");
            etUsername.setText(username);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        ((ImageView) getActivity().findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView)  getActivity().findViewById(R.id.tv_toolbar)).setText(getString(R.string.title_login));
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        getActivity().findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//              getActivity().setResult(CANCEL);
                getActivity().finish();
                getActivity().overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
            }
        });
    }

    @Override
    public void onResume() {
        assignData();
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    /**
     * 切换到注册验证页面
     */
    private void switchToVerifyFragment(int flag) {
        CountVerifyFragment fragment = new CountVerifyFragment();
        fragment.setFlag(flag);
        FragmentManager fm = getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.ll_content, fragment, "registerverify");
        tx.addToBackStack(null);
        tx.commit();
    }

    /**
     * 切换到找回密码页面
     */
    private void switchToFindPasswordFragment() {
        CountFindPasswordFragment fragment = new CountFindPasswordFragment();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.ll_content, fragment, "findpd");
        tx.addToBackStack(null);
        tx.commit();
    }

    private void login() {
        System.out.println("login");
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        if (!checkLogin(username, password)) {
            return;
        }
        showLoadingDialog(getActivity());
        interactUtil.login(username, password, true);
    }

    private boolean checkLogin(String username, String password) {
        if (username.equals("")) {
            logv(Tag, "手机号不能为空！");
            showToast(getActivity().getString(R.string.username_can_not_empty));
            return false;
        }
        if (password.equals("")) {
            logv(Tag, "密码不能为空！");
            showToast(getActivity().getString(R.string.password_can_not_empty));
            return false;
        }
        return true;
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {
    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(interactUtil.LOGIN)) {
            if (ret != 0) {
                SystemConstant.loginStatus = SystemConstant.Offline;
                Message msg = mHandler.obtainMessage();
                msg.obj = object;
                msg.what=0;
                mHandler.sendMessage(msg);
            } else if (ret == 0) {
                mHandler.sendEmptyMessage(1);
            }
        } else if (flag.equals(interactUtil.HEADICON)) {
            if (ret == 0) {
                mHandler.sendEmptyMessage(1);
            }
        }

    }
}
